using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Sirenix.OdinInspector;
using UnityEngine;

public class ReadPath : MonoBehaviour
{
    public Material material;
    private LineRenderer _lineRenderer;

    public Color color = Color.green;
    public string droneName;

    // private readonly UavPath _path = new UavPath();
    public string filePath;
    private List<Vector3> Points => (from Transform child in transform select child.position).ToList();

    private void Awake()
    {
        _lineRenderer = gameObject.AddComponent<LineRenderer>();
        _lineRenderer.material = material;
        _lineRenderer.startColor = color;
        _lineRenderer.endColor = color;
        _lineRenderer.startWidth = 0.1f;
        _lineRenderer.endWidth = 0.1f;
        _lineRenderer.positionCount = 0;
    }

    private void UpdateLineRenderer()
    {
        _lineRenderer.positionCount = Points.Count;
        _lineRenderer.SetPositions(Points.ToArray());
    }

    public void Update()
    {
        //记录物体运动轨迹，每隔distance距离记录一次
        UpdateLineRenderer();
    }


    [Button("清理路线")]
    void ClearPoints()
    {
        // 使用 for 循环遍历当前对象的所有子对象
        for (var i = transform.childCount - 1; i >= 0; i--)
        {
            // 删除子对象
            DestroyImmediate(transform.GetChild(i).gameObject);
        }
    }

    [Button("生成螺旋线上升的路线")]
    void GenerateBeautifulMathPath(float radius = 60f, float height = 30f, int steps = 50)
    {
        // 阿基米德螺旋线上升部分
        for (var i = 0; i < steps; i++)
        {
            var t = (float)i / steps;
            var angle = 2 * Mathf.PI * t * 5; // 旋转 5 圈
            var r = radius * t;
            var x = r * Mathf.Cos(angle);
            var y = t * height;
            var z = r * Mathf.Sin(angle);
            AddPointAtPosition(new Vector3(x, y, z));
        }

        // 直线下降部分
        var startDescend = Points[Points.Count - 1];
        var descendSteps = steps;
        var stepDownHeight = height / descendSteps;
        for (var i = 0; i < descendSteps; i++)
        {
            var y = startDescend.y - i * stepDownHeight;
            AddPointAtPosition(new Vector3(startDescend.x, y, startDescend.z));
        }
    }


    [Button("添加路径点")]
    private void AddPointAtPosition(Vector3 position)
    {
        _ = new GameObject
        {
            name = "Point" + (transform.childCount + 1),
            transform =
            {
                parent = transform,
                position = position
            }
        };
    }

    [Button("导出路径文件")]
    private void CreatePathFile()
    {
        var path = new UavPath(Points);
        var json = JsonConvert.SerializeObject(path, new VectorConverter());
        //写入文件
        filePath = System.IO.Path.Combine(Application.streamingAssetsPath, $"{droneName}.json");
        System.IO.File.WriteAllText(filePath, json);
        Debug.Log("路径文件已生成" + filePath);
    }


    [Button("读取路径文件")]
    private void ReadPathFile()
    {
        filePath = System.IO.Path.Combine(Application.streamingAssetsPath, $"{droneName}.json");

        // 检查文件是否存在
        if (System.IO.File.Exists(filePath))
        {
            ClearPoints();
            var json = System.IO.File.ReadAllText(filePath);
            var loadedPath = JsonUtility.FromJson<UavPath>(json);
            foreach (var point in loadedPath.points)
            {
                AddPointAtPosition(new Vector3(point.x, point.y, point.z));
            }

            Debug.Log("路径文件已读取并生成路线: " + filePath);
        }
        else
        {
            Debug.LogError("文件未找到: " + filePath);
        }
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.green;

        for (var i = 0; i < Points.Count; i++)
        {
            if (i != Points.Count - 1)
                Gizmos.DrawLine(Points[i], Points[i + 1]);
        }
    }
}